<template lang="pug">
  .step-2
    Spin(v-if="spinShow" size="large" fix)
    Form(v-if="formValidate_t2" ref="formValidate_t2" :model="formValidate_t2" :label-width="150")
      Row(type="flex" justify="start")
        Col(:md="{ span: 24 }" :lg="{ span: 12 }" :xl="{ span: 8 }" :xxl="{span: 6}")
          FormItem.ivu-form-item-required(label="法定名称：" prop="registerName")
            Input(v-model="formValidate_t2.registerName" :placeholder="isCheck?'未填写':'请输入'" :disabled="isCheck")
        Col(:md="{ span: 24 }" :lg="{ span: 12 }" :xl="{ span: 8 }" :xxl="{span: 6}")
          FormItem.ivu-form-item-required(label="统一社会信用代码：" prop="unifiedCreditCode")
            Input(v-model="formValidate_t2.unifiedCreditCode" :placeholder="isCheck?'未填写':'请输入'" :disabled="isCheck")
        Col(:md="{ span: 24 }" :lg="{ span: 12 }" :xl="{ span: 8 }" :xxl="{span: 6}")
          FormItem.ivu-form-item-required(label="纳税人性质：" prop="taxpayerType")
            Select(v-model="formValidate_t2.taxpayerType"  :placeholder="isCheck?'未填写':'请选择'" @on-change="taxpayerTypeChange" :disabled="isCheck")
              Option(v-for="(item, index) in customerTaxpayertype_arr" :value="parseInt(item.key)" :key="index") {{ item.value }}
        Col(:md="{ span: 24 }" :lg="{ span: 12 }" :xl="{ span: 8 }" :xxl="{span: 6}")
          Poptip(trigger="hover" word-wrap style="width:100%" content="温馨提示：社保、公积金、工资、个税、手续费属于代扣代缴项目，仅支持开具增值税普通发票。")
            FormItem.ivu-form-item-required(label="发票种类：" prop="invoiceType")
              Select(v-model="formValidate_t2.invoiceType"  placeholder="请选择" :disabled="isCheck" @on-change="invoiceTypeChange")
                template(v-for="(item, index) in customerInvoicetype_arr" :placeholder="isCheck?'未填写':'请选择'")
                  Option(v-if="item.key==='2'" :value="parseInt(item.key)" :disabled="formValidate_t2.taxpayerType === 2") {{ item.value }}
                  Option(v-else :value="parseInt(item.key)") {{ item.value }}
        Col(:md="{ span: 24 }" :lg="{ span: 12 }" :xl="{ span: 8 }" :xxl="{span: 6}")
          FormItem(label="注册地址：" :class="mustHave?'ivu-form-item-required':''")
            Input(v-model="formValidate_t2.registerAddress" :placeholder="isCheck?'未填写':'请输入'" :disabled="isCheck")
        Col(:md="{ span: 24 }" :lg="{ span: 12 }" :xl="{ span: 8 }" :xxl="{span: 6}")
          FormItem(label="电话：" :class="mustHave?'ivu-form-item-required':''")
            Input(v-model="formValidate_t2.phone" :placeholder="isCheck?'未填写':'请输入'" :disabled="isCheck")
        Col(:md="{ span: 24 }" :lg="{ span: 12 }" :xl="{ span: 8 }" :xxl="{span: 6}")
          FormItem(label="开户行名称：" :class="mustHave?'ivu-form-item-required':''")
            Input(v-model="formValidate_t2.bankName" :placeholder="isCheck?'未填写':'请输入'" :disabled="isCheck")
        Col(:md="{ span: 24 }" :lg="{ span: 12 }" :xl="{ span: 8 }" :xxl="{span: 6}")
          FormItem(label="开户行账号：" :class="mustHave?'ivu-form-item-required':''")
            Input(v-model="formValidate_t2.accountNo" :placeholder="isCheck?'未填写':'请输入'" :disabled="isCheck")
        Col(:md="{ span: 24 }" :lg="{ span: 12 }" :xl="{ span: 8 }" :xxl="{span: 6}")
          FormItem(label="发票接收人：" :class="isDZPP?'ivu-form-item-required':''")
            Input(v-model="formValidate_t2.invoiceReceiver" :placeholder="isCheck?'未填写':'请输入'" :disabled="isCheck")
        Col(:md="{ span: 24 }" :lg="{ span: 12 }" :xl="{ span: 8 }" :xxl="{span: 6}")
          FormItem(label="手机号码：" :class="isDZPP?'ivu-form-item-required':''" prop="phoneNo")
            Input(v-model="formValidate_t2.phoneNo" :placeholder="isCheck?'未填写':'请输入'" :disabled="isCheck")
        Col(:md="{ span: 24 }" :lg="{ span: 12 }" :xl="{ span: 8 }" :xxl="{span: 6}")
          FormItem(label="邮箱：" :class="isDZPP?'ivu-form-item-required':''" prop="email")
            Input(v-model="formValidate_t2.email" :placeholder="isCheck?'未填写':'请输入'" :disabled="isCheck")
        Col(:md="{ span: 24 }" :lg="{ span: 12 }" :xl="{ span: 8 }" :xxl="{span: 6}")
          FormItem(label="注册资本：")
            Input(v-model="formValidate_t2.registerCapital" :placeholder="isCheck?'未填写':'请输入'" :disabled="isCheck")
        Col(:md="{ span: 24 }" :lg="{ span: 12 }" :xl="{ span: 8 }" :xxl="{span: 6}")
          FormItem(label="成立时间：")
            DatePicker(v-model="formValidate_t2.foundedDate" type="date" :class="isCheck?'dis-datepicker':''" :placeholder="isCheck?'未填写':'请选择'" :disabled="isCheck")
        Col(:md="{ span: 24 }" :lg="{ span: 12 }" :xl="{ span: 8 }" :xxl="{span: 6}")
          FormItem(label="公司规模：")
            Select(v-model="formValidate_t2.size"  :placeholder="isCheck?'未填写':'请输入'" clearable :disabled="isCheck")
              Option(v-for="(item, index) in customerSize_arr" :value="parseInt(item.key)" :key="index") {{ item.value }}
        Col(:md="{ span: 24 }" :lg="{ span: 12 }" :xl="{ span: 8 }" :xxl="{span: 6}")
          FormItem(label="法定代表人：")
            Input(v-model="formValidate_t2.legalPerson" :placeholder="isCheck?'未填写':'请输入'" :disabled="isCheck")
        Col(:md="{ span: 24 }" :lg="{ span: 12 }" :xl="{ span: 8 }" :xxl="{span: 6}")
          FormItem(label="公司类型：")
            Select(v-model="formValidate_t2.companyType" :label-in-value="true"  :placeholder="isCheck?'未填写':'请选择'" clearable @on-change="companyTypeChange" :disabled="isCheck")
              Option(v-for="(item, index) in customerCompanytype_arr" :value="item.key" :key="index") {{ item.value }}
        Col(:md="{ span: 24 }" :lg="{ span: 12 }" :xl="{ span: 8 }" :xxl="{span: 6}")
          FormItem(label="所属行业：")
            Select(v-model="formValidate_t2.businessType" :label-in-value="true"  :placeholder="isCheck?'未填写':'请选择'" clearable @on-change="businessTypeChange" :disabled="isCheck")
              Option(v-for="(item, index) in customerBusinesstype_arr" :value="item.key" :key="index") {{ item.value }}
        Col(:md="{ span: 24 }" :lg="{ span: 12 }" :xl="{ span: 8 }" :xxl="{span: 6}")
          FormItem(label="备注：")
            Input(v-model="formValidate_t2.remarks" :placeholder="isCheck?'未填写':'请输入'" :disabled="isCheck")
      FormItem(label="经营范围：")
        Input(v-model="formValidate_t2.domain" type="textarea" :placeholder="isCheck?'未填写':'请输入'" :disabled="isCheck")
      FormItem(label="营业执照：")
        .d-flex
          .position-relative.mr-10(v-for="(item, index) in licenseAttachmentsArr" :key="index")
            img(:src="baseUrl + '/Customer/DownLoadAttachment?id=' + item.id" @click="previewImg(item.id, item.name)")
            Icon.img-close(v-if="!isCheck" type="md-close-circle" size="20" @click="deleteImg(item.id, index)")
          .position-relative.mr-10(v-if="!isCheck")
            Upload(
              ref="licenseUploadRef"
              :on-success="licenseUpload"
              :action="baseUrl+'/Customer/'+customerId+'/Upload'" :data="{categoryname: '营业执照副本'}"
              :format="['jpg','jpeg','png']"
              :show-upload-list="false")
              .license-img
                Icon( type="ios-image-outline" size="60")
          span(v-if="!isCheck") 支持jpg、jpeg、png格式
          span(v-if="isCheck && licenseAttachmentsArr.length < 1") 未上传
    //- .tab-footer.clearfix
    //-   Button.pull-right(v-if="isCheck" type="info" @click="reviseBtn") 修改
    //-   Button.pull-right(v-else type="info" @click="saveStep_2") 保存

</template>

<script>
import dataApi from '@/api/data.js'
import config from '@/config'
const baseUrl = process.env.NODE_ENV === 'development' ? config.baseUrl.dev : config.baseUrl.pro

export default {
  name: 'stpe_2',
  props: {
    customerId: String
  },
  data () {
    return {
      imgUrl: '',
      baseUrl: baseUrl,
      LicenseAttachmentsId: '', // 营业执照副本id
      licenseAttachmentsArr: [],
      mustHave: false, // 必填
      isDZPP: false, // 选择了电子发票-普票
      spinShow: false, // 加载中
      isCheck: true, // 是否处于查看状态
      formValidate_t2: null, // 营业执照信息
      customerTaxpayertype_arr: [], // 纳税人性质
      customerInvoicetype_arr: [], // 发票种类
      customerSize_arr: [], // 公司规模
      customerCompanytype_arr: [], // 公司类型
      customerBusinesstype_arr: [], // 所属行业
      // rules: {
      //   phoneNo: [
      //     { type: 'string', message: '请输入11位数的手机号码', pattern: /^\d{11}$/ }
      //   ],
      //   email: [
      //     { type: 'string', message: '请输入正确的邮箱', pattern: /^([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+\.[a-zA-Z]{2,3}$/ }
      //   ]
      // },
      rulesObj: {
        isRequireFalse: { required: false },
        isRequireTrue: { required: true, message: '不能为空' },
        phoneValid: { message: '请输入11位数的手机号码', trigger: 'change', pattern: /^\d{11}$/ },
        emailValid: {  message: '请输入正确的邮箱', trigger: 'change', pattern: /^([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+\.[a-zA-Z]{2,3}$/ },
      }
    }
  },
  computed: {
    // isDZPP () {
    //   return this.formValidate_t2.invoiceType == 3 ? true : false
    // }
    setRules () {
      let rules = {
        registerName: [this.rulesObj.isRequireTrue],
        unifiedCreditCode: [this.rulesObj.isRequireTrue],
        taxpayerType: [this.rulesObj.isRequireTrue],
        invoiceType: [this.rulesObj.isRequireTrue],
        // phone: [this.rulesObj.phoneValid],
        phoneNo: null,
        email: null
      }
      if (this.formValidate_t2.invoiceType == 3) {
        rules.phoneNo = [ this.rulesObj.phoneValid ]
        rules.email = [ this.rulesObj.emailValid ]
      } else {
        rules.phoneNo = [ this.rulesObj.isRequireFalse, this.rulesObj.phoneValid ]
        rules.email = [ this.rulesObj.isRequireFalse, this.rulesObj.emailValid ]
      }
      return rules
    }
  },
  mounted () {
    this.getEnum()
    this.getLicense()
    this.getLicenseAttachments()
  },
  methods: {
    licenseUpload (response) {
      this.getLicenseAttachments()
    },
    deleteImg (id, index) {
      dataApi.deleteAttachments({
        id: id
      }).then(res => {
        this.licenseAttachmentsArr.splice(index, 1)
        this.getLicenseAttachments()
      })
    },
    previewImg (id, name) {
      this.$emit('preview', {
        url: baseUrl + '/Customer/DownLoadAttachment?id=' + id,
        id: id,
        fileName: name
      })
    },
    getLicenseAttachments () {
      dataApi.getLicenseAttachments({
        id: this.customerId
      }).then(res => {
        console.log(res)
        if (res.data.success) {
          this.licenseAttachmentsArr = res.data.data
          // this.imgUrl = this.baseUrl + '/Customer/DownLoadAttachment?id=' + this.LicenseAttachmentsId
          //  dataApi.getDownLoadAttachment({
          //   id:id
          // }).then(res => {
          //   this.imgUrl =
          // })
        }
      })
    },
    getEnum () {
      let groupNames = 'customer.taxpayertype,customer.invoicetype,customer.size,customer.companytype,customer.businesstype'
      dataApi.getEnum({
        groupName: groupNames
      }).then((res) => {
        this.customerTaxpayertype_arr = this.getItems(res.data, 'customer.taxpayertype')
        this.customerInvoicetype_arr = this.getItems(res.data, 'customer.invoicetype')
        this.customerSize_arr = this.getItems(res.data, 'customer.size')
        this.customerCompanytype_arr = this.getItems(res.data, 'customer.companytype')
        this.customerBusinesstype_arr = this.getItems(res.data, 'customer.businesstype')
      })
    },
    getItems (arr, key) {
      let object = arr.find((item) => {
        return item.group === key
      })
      return object.items
    },
    // 获取营业执照信息
    getLicense () {
      this.spinShow = true
      dataApi.getLicense({
        id: this.customerId
      }).then(res => {
        if (res.data.success) {
          this.formValidate_t2 = res.data.data
          if (this.formValidate_t2.invoiceType === 2) {
            this.mustHave = true
          }
          if (this.formValidate_t2.invoiceType === 3) {
            this.isDZPP = true
          }
        } else {
          this.formValidate_t2 = {
            customerId: this.customerId,
            registerName: '', // 法定名称
            unifiedCreditCode: '', // 统一社会信用代码
            taxpayerType: '', // 纳税人性质
            invoiceType: '', // 发票种类
            registerAddress: '', // 注册地址
            phone: '', // 电话
            bankName: '', // 开户行名称
            accountNo: '', // 开户行账号
            invoiceReceiver: '', // 发票接收人
            phoneNo: '', // 手机号码
            email: '', // 邮箱
            registerCapital: '', // 注册资本
            foundedDate: '', // 成立时间
            size: '', // 公司规模
            legalPerson: '', // 法定代表人
            companyType: '', // 公司类型ID
            companyTypeName: '', // 公司类型名称
            businessType: '', // 所属行业ID
            businessTypeName: '', // 所属行业名称
            domain: '', // 经营范围
            rowversion: '' // 新为空,修改时原值返回
          }
        }
        this.spinShow = false
      })
    },
    // 纳税人性质选择
    taxpayerTypeChange (val) {
      console.log(val)
      this.formValidate_t2.invoiceType = ''
    },
    // 发票选择
    invoiceTypeChange (val) {
      console.log('发票选择改变', val)
      // this.formValidate_t2.invoiceReceiver = ''
      // this.formValidate_t2.phoneNo = ''
      // this.formValidate_t2.email = ''
      if (val === 2) {
        console.log('选择了 专用发票')
        this.mustHave = true
        this.isDZPP = false
      } else if (val == 3) {
        this.mustHave = false
        this.isDZPP = true
        console.log('选择了 电子发票-普票 新增的三个字段必填')
      } else {
        console.log('选择了 普通发票')
        this.mustHave = false
        this.isDZPP = false
      }
    },
    // 公司类型选择
    companyTypeChange (val) {
      if (val) {
        this.formValidate_t2.companyTypeName = val.label
      }
    },
    // 所属行业选择
    businessTypeChange (val) {
      if (val) {
        this.formValidate_t2.businessTypeName = val.label
      }
    },
    // 修改
    reviseBtn () {
      this.isCheck = false
    },
    // 保存
    saveStep_2 () {
      dataApi.postLicense(this.formValidate_t2).then((res) => {
        if (res.data.success) {
          this.$Message.success(res.data.message)
          this.isCheck = true
          this.formValidate_t2.rowVersion = res.data.data.rowversion
        } else {
          this.$Message.error({
            content: res.data.message,
            duration: 10,
            closable: true
          })
        }
      })
      // this.$refs.formValidate_t2.validate((valid) => {
      //   if (valid) {
      //   }
      // })
    }
  }

}
</script>

<style lang="less" scoped>
  .d-flex{
    display: flex;
    flex-wrap: wrap;
    align-items: center;
  }
  .position-relative{
    .license-img{
      width: 100%;
      height: 100%;
      cursor: pointer;
      line-height: 80px;
      text-align: center;
    }
    img{
      width: 100%;
      height: 100%;
      object-fit: cover;
    }
    .img-close{
      position: absolute;
      top: -8px;
      right: -8px;
      z-index: 9;
      cursor: pointer;
    }
  }
</style>
